package com.jielihaofeng.cosmic.form.control;

import com.jielihaofeng.cosmic.event.BeforeClickEvent;
import com.jielihaofeng.cosmic.event.ClickEvent;
import com.jielihaofeng.cosmic.listener.ClickListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Johnnie Wind
 * @description
 * @date 2021/11/29 10:08
 */
public class Button extends Control {
    protected List<ClickListener> buttonClickListeners = new ArrayList();

    public Button() {
    }

    public Button(String key) {
        super(key);
    }

    public void addClickListener(ClickListener listener) {
        this.buttonClickListeners.add(listener);
    }

    public void click() {
        BeforeClickEvent e = new BeforeClickEvent(this);
        this.fireBeforeClick(e);
        if (!e.isCancel()) {
            this.fireClick(e);
        }

    }

    private void fireClick(ClickEvent e) {
        if (this.buttonClickListeners != null) {
            Iterator iterator = this.buttonClickListeners.iterator();

            while (iterator.hasNext()) {
                ClickListener l = (ClickListener) iterator.next();
                l.click(e);
            }
        }

    }

    private void fireBeforeClick(BeforeClickEvent e) {
        Iterator iterator = this.buttonClickListeners.iterator();

        while (iterator.hasNext()) {
            ClickListener l = (ClickListener) iterator.next();
            l.beforeClick(e);
        }

    }
}
